<template>
  <div>
    <div style="display: inline">
    <el-input
        placeholder="搜索..."
        size="mini"
        style="width: 300px;margin: 0px;padding: 0px;">
    </el-input>
    <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search">搜索
    </el-button>      
    <el-button type="primary" size="mini" icon="el-icon-plus" @click="showAddRoleView">添加角色
    </el-button>      
      
    </div>
    <el-table
      ref="multipleTable"
      :data="roleList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      tooltip-effect="dark"
      style="width: 100%"
      stripe
      border
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="id"
        label="角色id"
        width="200">
      </el-table-column>
      <el-table-column
        prop="name"
        label="角色名称"
        width="200">
      </el-table-column>
      <el-table-column
        prop="roleKey"
        label="角色标识符"
        width="200">
      </el-table-column>
      <el-table-column
        prop="status"
        label="角色状态"
        width="200"
        sortable>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="200"
        sortable>
      </el-table-column>
      <el-table-column 
        label="操作"
        width="200">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="roleList.length">
      </el-pagination>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="角色标识符" prop="roleKey">
          <el-input v-model="form.roleKey"></el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-input v-model="form.status"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="permissionIds">
          <el-tree :data="permissionTree" 
                   :props="defaultProps"
                   :default-checked-keys="form.permissionIds"
                    node-key="id"
                    ref="tree"
                    show-checkbox
                    highlight-current
                   @check-change="handleCheckChange"
                   @node-click="handleNodeClick">
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addRole(form)">确 定</el-button>
      </span>
    </el-dialog>

  </div>
  
</template>

<script>
  export default {
    data() {
      return {
        roleList: [],
        permissionTree: [],
        currentPage: 1,
        pageSize: 20,
        multipleSelection: [],
        dialogTitle: '',
        dialogVisible: false,
        form: {
          name: '',
          roleKey: '',
          status: '',
          permissionIds: [],
        },
        index: '',
        row: '',
        defaultProps: {
          children: 'children',
          label: 'name'
        },
      }
    },

    created () {
      // 组件创建完后获取数据，
      // 此时 data 已经被 observed 了
      this.getRoleList()
    },

    // watch: {
    //   // 如果路由有变化，会再次执行该方法
    //   '$route': 'getUserList'
    // },

    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleEdit(index, row) {
        let permissions = this.roleList[index].permissions;
        let permissionIds = [];
        for (let index in permissions) {
          let id = permissions[index].id;
          permissionIds.push(id);
        }
        this.getPermissionTree();
        this.form.name = row.name;
        this.form.roleKey = row.roleKey;
        this.form.status = row.status;
        this.form.permissionIds = permissionIds;
        this.dialogTitle = "编辑角色";
        this.dialogVisible = true;
        this.index = index;
        this.row = row;
        
      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除[' + row.name + '], 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteRequest("/role/" + row.id).then(data=> {
            this.$message({
              message: '删除角色成功',
              type: 'success'
            });
            this.roleList.splice(index, 1);
          })
        })
        
      },
      handleSizeChange(size) {
        this.pageSize = size;
      },
      handleCurrentChange(currentPage){
        this.currentPage = currentPage;
      },
      getRoleList(){
        this.getRequest("/role").then(data=> {
            this.roleList = data;
        })
      },
      getPermissionTree(){
        this.getRequest("/permission/tree").then(data=> {
            this.permissionTree = data;
        })
      },
      showAddRoleView(){
        this.initFormData();
        this.dialogTitle = "添加用户";
        this.getPermissionTree();
        this.dialogVisible = true;
        
      },
      addRole(form){

        if (!this.row.id) {
          //添加
          this.form.permissionIds = this.$refs.tree.getCheckedKeys();
          this.postRequest("/role", JSON.stringify(form)).then(data=> {
            this.$message({
              message: '添加成功，新增的角色为：' +　data.name,
              type: 'success'
            });
            this.roleList.push(data);
            this.dialogVisible = false;
          })      
        }else{
          this.form.permissionIds = this.$refs.tree.getCheckedKeys();
          let roleForm = {};
          roleForm.name = this.form.name;
          roleForm.roleKey = this.form.roleKey;
          roleForm.status = this.form.status;
          roleForm.permissionIds = this.form.permissionIds;
          roleForm.id = this.row.id;
          console.log(JSON.stringify(roleForm));
          //修改
          this.putRequest("/role/" + roleForm.id, JSON.stringify(roleForm)).then(data=> {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.roleList.splice(this.index, 1, data);
            this.index = '';
            this.row = '';
            this.dialogVisible = false;
          })              
        }      
      },
      cancel(){
        this.dialogVisible = false;
        this.initFormData();
      },
      initFormData(){
        this.form = {
          name: '',
          roleKey: '',
          status: '',
        };
        this.index = '';
        this.row = '';
      },
      handleNodeClick(data) {
        console.log(data);
      },
      handleCheckChange(data, checked, indeterminate) {
        console.log(data, checked, indeterminate);
      },

    }
  }
</script>